var tabTemplate = "<li><a href='#{href}'>#{label}</a></li>";
var tabs;
var alreadySelectedFirst = false;

function download(downloadServer, title, keywords, div_container_id)
{
    createTabs(div_container_id);
    grapLinks(downloadServer, title, keywords);
}


function grapLinks(downloadServer, title, keywords)
{
    keywords = keywords.split("@");
    var inTitle = keywords[0];
    if(inTitle != null && inTitle != "")
        inTitle = '-' + inTitle;

    var tabs = keywords[1];
    var badKeywords = keywords[2];
    var suburl = encode_term(title + inTitle) + "/" + tabs + "?jsonp_callback=?";

    getDownloadLinks(downloadServer + "/d/isohunt/" + suburl);
    getDownloadLinks(downloadServer + "/d/tpb/" + suburl);
    getDownloadLinks(downloadServer + "/d/filesTube/" + suburl);
    getDownloadLinks(downloadServer + "/d/ahashare/" + suburl);
    getDownloadLinks(downloadServer + "/d/kat/" + suburl);
    getDownloadLinks(downloadServer + "/d/subscene/" + suburl);
}

function getDownloadLinks(url)
{
    var downloadAPI = url;
    $.getJSON(downloadAPI, 'firstname=Jeff', function(data)
    {

        for (var k in data)
        {
            if (data.hasOwnProperty(k))
            {
                var rows = "";
                $(data[k]).each(function(row)
                {
                    var link = '<a href="{0}" target="_blank"><img src="{2}" /> {1}</a>';
                    link = link.replace("{0}", data[k][row].href);
                    link = link.replace("{1}", data[k][row].title);
					link = link.replace("{2}", data[k][row].favicon);

                    var trow = '<tr onclick="window.open(\'{4}\');"><td style="width: 100%">{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>';
                    trow = trow.replace('{0}', link);

                    trow = trow.replace('{1}', data[k][row].size);
                    trow = trow.replace('{2}', data[k][row].seeds);
                    trow = trow.replace('{3}', data[k][row].peers);
                    trow = trow.replace('{4}', data[k][row].href);

                    rows += trow;
                });
                addDownloadTab(k, rows);


            }
        }
    });
}

function encode_term(term)
{
    var encoded_url = term.replace(/[\s]/g, '-');
    encoded_url = encoded_url.replace(/[^a-zA-Z0-9 -]/g, '');
    encoded_url = encoded_url.replace(/-/g, '+');
    return encoded_url;
}


function addDownloadTab(tab_title, rows)
{
    id = "tabs-" + tab_title;
    if ($("#" + id).length > 0)
    { //if tab already exists just append links
        $("#" + id + ' table').append(rows);
    }
    else //if tab not created, creat it and append links
    {
        var label = tab_title,
            li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label));
        tabs.find(".ui-tabs-nav").append(li);
        tabs.append("<div id='" + id + "'><table><thead><tr><th>Title</th><th>Size</th><th>Seeds</th><th>Peers</th></tr></thead><tbody>" + rows + "</tbody></table></div>");
        tabs.tabs("refresh");
        if (!alreadySelectedFirst)
        {
            tabs.tabs("option", "active", 0);
            alreadySelectedFirst = true;
        }
    }

    $('#' + id + ' table').tablesorter({ sortList: [[2,1]] });
}

function createTabs(div_container_id)
{
    if(tabs)
        tabs.tabs( "destroy" );
    $("#" + div_container_id).html("");
    $("#" + div_container_id).append("<ul></ul>");
    tabs = $("#" + div_container_id).tabs();

    tabs.bind("keyup", function (event)
    {
        if (event.altKey && event.keyCode === $.ui.keyCode.BACKSPACE) {
            var panelId = tabs.find(".ui-tabs-active").remove().attr("aria-controls");
            $("#" + panelId).remove();
            tabs.tabs("refresh");
        }
    });
}